<template>
  <panel-header :route="route"/>
  <div style="background-color: white;margin-top: 10px;">
    <el-button type="primary" size="small" style="margin: 5px;" icon="Plus" @click="open(null)">新增</el-button>
    <el-button type="danger" size="small" style="margin: 5px;" icon="Delete" @click="deleteBatch">删除</el-button>
  </div>

  <el-table :data="listData.list" style="width: 100%" @selection-change="handleSelectionChange" stripe>
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="id" width="60"/>
    <el-table-column prop="name" label="昵称" width="80"/>
    <el-table-column prop="avatar" label="头像">
      <template #default="scope">
        <el-image
            :src="scope.row.avatar"
            style="width: 80px;height: 80px"
        ></el-image>
      </template>
    </el-table-column>
    <el-table-column prop="sex" label="性别" width="55"/>
    <el-table-column prop="mobile" label="手机号"/>
    <el-table-column prop="active" label="状态">
      <template #default="scope">
        <el-tag :type="scope.row.active?'success':'danger'">{{scope.row.active?'正常':'异常'}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="create_time" label="创建时间">
      <template #default="scope">
        <div class="flex-box">
          <el-icon><Clock/></el-icon>
          <span style="margin-left: 10px">{{scope.row.create_time}}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="open(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination-info">
    <el-pagination
        style="float:right"
        v-model:current-page="paginationData.pageNum"
        v-model:page-size="paginationData.pageSize"
        size="small"
        :background="false"
        layout="total,prev, pager, next"
        :total="listData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog
      :title=title
      v-model="dialogVisable"
      :before-close="beforeClose"
      width="500"
      label-width="100">
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
    >
      <el-form-item prop="id" v-show=" false">
        <el-input v-model="form.id"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input placeholder="请输入昵称" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-button type="primary" @click="dialogImgVisable=true" v-if="!form.avatar" >点击上传</el-button>
        <el-image v-else :src="form.avatar" @click="dialogImgVisable=true" style="width: 100px;height: 100px"></el-image>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择性别">
          <el-option label="男" value="1"/>
          <el-option label="女" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="form.age" :min="18" :max="50" style="width: 150px"/>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input placeholder="请输入手机号" v-model="form.mobile"></el-input>
      </el-form-item>
      <el-form-item label="是否生效" prop="active">
        <el-radio-group v-model="form.active">
          <el-radio :value="0" size="large" checked>失效</el-radio>
          <el-radio :value="1" size="large">生效</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="beforeClose">取消</el-button>
      <el-button type="primary" @click="submit(formRef)">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog
      title="选择头像"
      v-model="dialogImgVisable"
      :before-close="beforeClose"
      width="680"
      label-width="100">
    <div class="image-list">
      <div v-for="(item,index) in avatarData" :key="item.name" @click="selectAvatar = index" class="img-box">
        <div class="img-box-select" v-if="selectAvatar === index">
          <el-icon color="white"><Check/></el-icon>
        </div>
        <el-image :src="item.url" style="width: 148px;height: 148px"/>
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogImgVisable=false">取消</el-button>
      <el-button type="primary" @click="submitImage">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref,reactive,onMounted,nextTick} from "vue";
import {photoList, companion, companionList,deleteCompanion} from "../../../api/index";
import {Check, Clock} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import dayjs from "dayjs";
import PanelHeader from "../../../components/panelHeader.vue";
import {useRoute} from 'vue-router'
import { toRaw } from 'vue'


const route = useRoute()

//陪护师信息
const listData = reactive({
  List:[],
  total:0,
  ids:[]
})

//头像信息
const avatarData = ref([])
//头像选中
const selectAvatar = ref('')

onMounted(()=>{
  photoList().then(({data})=>{
    avatarData.value = data.data
  })
  companionData(paginationData)

})
//获取陪护师列表
const companionData = async ()=>{
   companionList(paginationData).then(({data})=>{
     const {list,total} = data.data
     listData.list=list
     listData.total= total
     //时间格式化
     listData.list.forEach(item=>{item.create_time=dayjs(item.create_time).format('YYYY-MM-DD')})
     //性别
     listData.list.forEach(item=>{item.sex=item.sex==='1'?'男':'女'})
  })
}
//分页数据
const paginationData=reactive({
  pageNum:1,
  pageSize:10
})
//改变分页
const handleSizeChange=(val) => {
  paginationData.pageSize=val
  companionData(paginationData)
}
const handleCurrentChange=(val) => {
  paginationData.pageNum=val
  companionData(paginationData)
}

//表单绑定数据
const formRef = ref(null);
const form = reactive({
  id: '',
  name: '',
  avatar: '',
  sex: '',
  age: 18,
  mobile: '',
  active: 0
})

//控制对话框是否可见
const dialogVisable = ref(false);
const dialogImgVisable = ref(false);
//控制对话框title
const title = ref('创建陪护师')
//关闭对话框前的操作
const beforeClose = () => {
  dialogVisable.value = false;
  dialogImgVisable.value = false;
  formRef.value.resetFields();

};

//校验规则
const rules = reactive({
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  avatar: [
    { required: true, message: '请选择头像', trigger: 'change' },
  ],
})

//提交表单
const submit = async(formRef) => {
  if(!formRef) return
  await formRef.validate((valid, fields)=>{
    if(valid){
      //调用接口
      companion(form).then(({data})=>{
        if(data.code === 10000){
          ElMessage.success(data.data)
          companionData(paginationData)
          beforeClose();

        }else{
          ElMessage.error(data.message)
        }
      })
    }else{
      console.log("error commit",fields)
    }
  })
}
//提交图片
const submitImage = async() => {
  form.avatar = avatarData.value[selectAvatar.value].url
  dialogImgVisable.value = false;

}

//打开对话框
const open = (data) => {
  nextTick(()=>{
    if(data){
      title.value="修改陪护师信息"
      Object.assign(form,data)
      dialogVisable.value = true;
    }else{
      title.value="创建陪护师"
      dialogVisable.value = true;
    }
  })

}
const selectIds = ref([])
const handleSelectionChange=(rows)=>{  //返回所有选中的行对象数组
  //从选中的行对象数组中取出所有的id组成一个新的数组
  selectIds.value = rows
}
const deleteBatch=()=> {
  if (selectIds.value.length === 0) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，你确认删除吗', '删除确认', {type: 'warning'}).then(() => {
    //转为普通数组
    deleteCompanion({ id: selectIds.value }).then(({ data }) => {
      if (data.code === 10000) {
        ElMessage.success("删除成功")
        companionData()

      } else {
        ElMessage.error(data.message)
      }
    })

  }).catch()
}

</script>
<style lang="less" scoped>
.pagination-info{
  height: 50px;
  line-height: 50px;
  padding-left:10px;
  background-color: white;
  text-align: right;
}
.image-list{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .img-box{
    position: relative;
    .img-box-select{
      position: absolute;
      top: 0;
      left: 0;
      width: 24px;
      height: 24px;
      background-color: #67c23a;
      z-index:999;
      display:flex;
      justify-content: center;
      align-items: center;
    }
    .el-image{
      margin-right: 10px;
      margin-bottom: 10px;

    }

  }
}

</style>
